<template>
  <collapse-card title="案件人员信息列表">
    <template #header-right>
      <div>
        <el-button type="primary" @click="addPeople">新增人员</el-button>
        <el-button type="primary" @click="handleImport">批量导入</el-button>
        <el-button type="primary" @click="onDownload">下载模板</el-button>
        <el-button type="primary" @click="onPersonInfo">获取人员信息</el-button>
      </div>
    </template>
    <div class="personnel-list">
      <el-table :data="data" style="width: 100%">
        <el-table-column label="序号" type="index" width="70" fixed="left" />
        <el-table-column label="操作" width="100" fixed="left">
          <template slot-scope="{ $index }">
            <el-button @click="deleteRow($index)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="xm" label="姓名" width="130">
          <template slot-scope="{ row }">
            <el-input v-model="row.xm" :maxLength="10" />
          </template>
        </el-table-column>
        <el-table-column prop="sfzh" label="身份证号" width="240">
          <template slot-scope="{ row, $index }">
            <div class="valid-box">
              <div class="el-icon-warning" v-if="data[$index].idError"></div>
              <el-input v-model="row.sfzh" :maxLength="18" @blur="onCheck(row)" />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="xb" label="性别" width="100">
          <template slot-scope="{ row }">
            <dg-select v-model="row.xb" :data="constant.DM_SEX" placeholder="" />
          </template>
        </el-table-column>
        <el-table-column prop="hjd" label="户籍地" width="220">
          <template slot-scope="{ row }">
            <el-input v-model="row.hjd" :maxLength="50" />
          </template>
        </el-table-column>
        <el-table-column prop="xzd" label="现住地" width="220">
          <template slot-scope="{ row }">
            <el-input v-model="row.xzd" :maxLength="50" />
          </template>
        </el-table-column>
        <el-table-column prop="_ryys" label="人员要素" width="380">
          <template slot-scope="{ row }">
            <div>
              <div v-for="(item, _i) in row._ryys" :key="_i" class="input-select">
                <div>
                  <el-input v-model="item.ysnr" :maxLength="50">
                    <el-select v-model="item.yslx" slot="prepend" placeholder="请选择要素">
                      <el-option
                              :label="yaosu.label"
                              :value="yaosu.value"
                              v-for="yaosu in yaosuSelect"
                              :key="yaosu.value"
                      />
                    </el-select>
                  </el-input>
                </div>
                <div class="btngroup">
                  <el-button class="sub" @click="onAddYaosu(row)">
                    <i class="el-icon-plus"></i>
                  </el-button>
                  <el-button class="sub" :disabled="row._ryys.length === 1" @click="onDeleteYaosu(row, _i)">
                    <i class="el-icon-minus"></i>
                  </el-button>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="wklx" label="稳控类型" width="180">
          <template slot-scope="{ row }">
            <dg-select v-model="row.wklx" clearable :data="constant.BM_WKLX" />
          </template>
        </el-table-column>
        <el-table-column prop="_wkdw" label="稳控单位" width="180">
          <template slot-scope="{ row }">
            <dg-tree-drop
                 v-model="row._wkdw"
                 :code="BM_DEPT"
                 :props="props" 
                 lazy-load
                 filterable 
                 clearable
                 value-name="value"
                 label-name="label"
                 style="width: 100%"
            ></dg-tree-drop>
            <!-- <el-cascader v-model="row._wkdw" :options="constant.BM_DEPT" :show-all-levels="false" clearable/> -->
            <!-- <dg-select v-model="row.wkdw" clearable lazy-load :data="constant.BM_DEPT" /> -->
          </template>
        </el-table-column>
        <el-table-column prop="gzqk" label="工作情况" width="300">
          <template slot-scope="{ row }">
            <el-input v-model="row.gzqk" :maxLength="200" />
          </template>
        </el-table-column>
      </el-table>
    </div>
  </collapse-card>
</template>
<script>
import { mapState } from 'vuex';
import exportApi from '@/api/exportApi';
import { isIdCard, CheckIDCard } from '@/components/FeatureExtr/data-process';
import { factorTypes, getPersonInfo, caseUserInfoSearch } from '@/api/common';
import CollapseCard from '@/components/layout/CollapseCard';
import { treeFather } from '@/utils/common';
import { BM_DEPT } from '@/common/codeDic';
export default {
  name: 'CaseList',
  components: {
    CollapseCard
  },
  data() {
    return {
      asjryxxDeleteList: [],
      fileHolderList: [],
      yaosuSelect: [],
      // 案事件人员列表数据
      data: [],
      oldData: [], // 上次保存前的数据
      // 上传的文件列表
      fileListUpload: [],
      flowId: '',
      props: {
           value: "value"
                },
      BM_DEPT,
    };
  },
  computed: {
    ...mapState(['constant']),
    isEidt() {
      return this.$route.meta.isEdit;
    }
  },
  props: {
    // 主流程id
    id: {
      type: String
    },
    peopleList: {
      type: Array,
      default: () => []
    },
    operater: {
      type: Boolean,
      default: true
    }
  },
  watch: {
    peopleList: {
      deep: true,
      immediate: true,
      handler(val) {
        // 转换数据格式
        const getysnrs = (arr) => {
          const _ryys = [];
          arr.forEach((child) => {
            child.ysnr.forEach((ysnr) => {
              _ryys.push({ yslx: child.yslx, ysnr });
            });
          });
          return _ryys;
        };
        this.data.forEach((item) => {
          const _i = val.findIndex((child) => child.sfz[0] === item.sfzh);
          if (item.sfzh && _i > -1) {
            const _ryys = getysnrs(val[_i].ysList);
            // 过滤已经存在的相同要素
            _ryys.forEach((ele) => {
              if (!this.onIsExitYaosu(item._ryys, ele)) item._ryys.push(ele);
            });
            item.xm = val[_i].xm[0];
            val.splice(_i, 1);
          }
        });
        val.forEach((item) => {
          this.data.push({
            flowId: this.flowId,
            xm: item.xm[0],
            xb: '',
            sfzh: item.sfz[0],
            hjd: '',
            xzd: '',
            _ryys: getysnrs(item.ysList),
            wklx: '',
            _wkdw: '',
            wkdw: '',
            gzqk: ''
          });
        });
      }
    }
  },
  mounted() {
    factorTypes().then(({ data }) => {
      this.constant.only_ys.forEach((item) => {
        const _i = data.findIndex((child) => child.value === item);
        if (_i > -1) {
          data.splice(_i, 1);
        }
      });
      this.yaosuSelect = data;
    });
    if (this.id) {
      this.flowId = this.id;
      this.getList();
    }
  },
  methods: {
    async handleId(id, component) {
      this.flowId = id;
      await this.getList();
      component === 'case' && this.handleImport();
    },
    /**
     * 获取关联的人员数据
     */
    getList() {
      let that = this;
      caseUserInfoSearch({
        page: 0,
        size: 200,
        searchCondition: JSON.stringify([{ name: 'flow_Id', op: '=', value: this.flowId }])
      }).then(({ data }) => {
        for (let i =0,len=data.content.length; i < len; i++){
          let item = data.content[i];
          item._ryys = item.ryys ? JSON.parse(item.ryys) : [{ yslx: '', ysnr: '' }];
          // item._wkdw = treeFather(this.constant.BM_DEPT, item.wkdw);
          item._wkdw = item.wkdw;
          that.$set(that.data, i, item);
        }

        // 保存接口查询的列表数据
        let oldData = JSON.parse(JSON.stringify(that.data));
        that.$set(that,"oldData",oldData);
      });
    },
    /**
     * 删除人员
     */
    deleteRow(_i) {
      this.$confirm('此操作将删除数据, 是否继续?').then(() => {
        if (this.$route.params.id && this.data[_i].id) {
          this.asjryxxDeleteList.push(this.data[_i].id);
        }
        this.data.splice(_i, 1);
      });
    },
    /**
     * 添加人员
     */
    addPeople() {
      this.data.push({
        flowId: this.flowId,
        xm: '',
        xb: '',
        sfzh: '',
        hjd: '',
        xzd: '',
        _ryys: [{ yslx: '', ysnr: '' }],
        wklx: '',
        _wkdw: '',
        wkdw: '',
        gzqk: ''
      });
    },
    /**
     * 提交前验证身份信息
     * isDraft为草稿时不做验证
     */
    onValidIdcard(isDraft) {
      return new Promise((resolve, reject) => {
        for (let i = 0; i < this.data.length; i++) {
          if (isDraft === '0') {
            // 处理异常身份证号
            if (!isIdCard(this.data[i].sfzh)) {
              this.$set(this.data[i], 'idError', true);
              this.$message.warning('案件人员身份证格式错误或重复，请检查');
              reject(false);
              return;
            } else {
               // 处理重复身份证号
              const repeatArr = (item) => this.data.filter((ele) => ele.sfzh === item.sfzh);
              const sameEle = repeatArr(this.data[i]);
              if (sameEle.length > 1) {
                this.$message.warning('案件人员身份证重复');
                sameEle.forEach((ele) => {
                  this.$set(ele, 'idError', true);
                });
                reject(false);
                return;
              } else {
                // 处理稳控单位
                const wkdw = this.data[i]._wkdw;
                if (wkdw && wkdw.length) {
                  this.data[i].wkdw = wkdw;
                }
                // 处理人员要素
                const ryys = this.data[i]._ryys;
                if (ryys.length === 1 && !ryys[0].yslx) {
                  this.data[i].ryys = null;
                } else {
                  this.data[i].ryys = JSON.stringify(this.data[i]._ryys);
                }
              }
            }
          } else {
            this.data[i].ryys = JSON.stringify(this.data[i]._ryys);
          }
        }
        resolve(this.data);
      });
    },
    /**
     * 身份证验证
     */
    onCheck(item) {
      if (CheckIDCard(item.sfzh)) {
        this.$set(item, 'idError', false);
      }
    },
    /**
     * 添加要素
     */
    onAddYaosu(row) {
      row._ryys.push({ yslx: '', ysnr: '' });
    },
    /**
     * 删除要素
     */
    onDeleteYaosu(row, i) {
      row._ryys.splice(i, 1);
    },
    /**
     * 要素信息是否已存在
     */
    onIsExitYaosu(item, newYaosu) {
      const sameSelect = item.find((item) => item.yslx === newYaosu.yslx);
      if (!sameSelect) return false;
      return sameSelect.ysnr === newYaosu.ysnr;
    },
    /**
     * 获取人员要素信息
     */
    onPersonInfo() {
      const sfzhs = this.data.map((item) => item.sfzh);
      const loadingInstance = this.$loading({
        lock: true,
        text: '获取中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      getPersonInfo({ sfzhs: sfzhs.join(), flowId: this.flowId })
        .then(({ data }) => {
          data.forEach((item) => {
            const person = this.data.find((child) => child.sfzh === item.sfzh);
            if (person) {
              Object.keys(person).forEach((child) => {
                if (['_ryys', 'ryys'].includes(child)) {
                  const _ryys = JSON.parse(item.ryys);
                  _ryys.forEach((ele) => {
                    if (!this.onIsExitYaosu(person._ryys, ele)) {
                      person._ryys.unshift(ele);
                    }
                  });
                } else if (!person[child]) {
                  person[child] = item[child];
                }
              });
            }
          });
          loadingInstance.close();
        })
        .catch(() => {
          loadingInstance.close();
          // this.$message.warning('获取失败');
          this.$message.warning('无关联信息');
        });
    },
    /**
     * 下载模板
     */
    onDownload() {
      exportApi.downloadFile({ url: '/v1/caseUserInfo/downloadUserInfoTemplate', name: '案件人员模板.xlsx' });
    },
    /**
     * 比较数据
     */
    handleDataCompare(newData, oldData){
      return JSON.stringify(newData) == JSON.stringify(oldData);
    },
    /**
     * 批量导入
     */
    handleImport() {
      if (!this.flowId || !this.handleDataCompare(this.data,this.oldData)) {
        this.$confirm('批量导入需要先保存信息，是否保存信息?').then(() => {
          this.$emit('saveInfo', 0, '1','case');
        });
      } else {
        let that_ = this;
        var layer = this.$dgLayer({
          title: '批量新增成员',
          content: require('./BatchImport'),
          maxmin: false,
          props: {
            typename: '案事件人员导入模板',
            params: {
              flowId: this.flowId
            },
            id: 'ryImp_template'
          },
          on: {
            success() {
              // 导入成功需要清除缓存人员信息后进行重新查询，否则会有重复人员
              that_.data = [];
              that_.getList();
              layer.close(layer.dialogIndex);
            }
          },
          cancel: function (index, layero) {
            // 关闭对应弹窗的ID
            layer.close(index);
            return false;
          },
          area: ['960px', '']
        });
      }
    }
  }
};
</script>

<style scoped lang="scss">
.personnel-list {
  .input-select {
    display: flex;
    margin-bottom: 12px;
    .btngroup {
      display: flex;
      width: 30%;
      margin-left: 8px;
      .sub {
        width: 32px;
        height: 32px;
        min-width: 32px;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
    .el-select {
      /deep/.el-input {
        width: 110px;
        input {
          padding-right: 12px;
        }
      }
    }
    &:last-child {
      margin-bottom: 0;
    }
  }
}
</style>
